package com.ztc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import com.aspose.words.BreakType;
import com.aspose.words.Document;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.License;
import com.aspose.words.Paragraph;
import com.aspose.words.ParagraphAlignment;
import com.aspose.words.SaveFormat;
import com.aspose.words.Section;
import com.aspose.words.StyleIdentifier;

/**
 * @类名：AsposeWordUtil.java
 * @作者：李晓平
 * @时间：2018年7月19日 下午4:39:32
 * @描述：生成目录工具类
 */
public class AsposeWordUtil {

	/**
	 * 加载证书
	 * @return
	 */
	private static boolean getLicense() {
        boolean result = false;
        try {
        	InputStream is = AsposeWordUtil.class.getResourceAsStream("/license.xml");
//          InputStream is = AsposeWordUtil.class.getClassLoader().getResourceAsStream("license.xml"); //  license.xml应放在..\WebRoot\WEB-INF\classes路径下
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
	
	
	public static void regenFile(String filePath) throws Exception {
		if (!getLicense()) { // 验证License 若不验证则会有水印产生
			return;
		}
		Document doc = new Document(filePath);	
		DocumentBuilder builder = new DocumentBuilder(doc);
		doc.save(filePath);
	}
	
	/**
	 * 生成目录
	 * @param filePath
	 * @throws Exception
	 */
	public static void generateCatalog(String filePath, int type) throws Exception {
		if (!getLicense()) { // 验证License 若不验证则会有水印产生
			return;
		}
		Document doc = new Document(filePath);
	
		DocumentBuilder builder = new DocumentBuilder(doc);
		
//		//重设表格的样式
//		NodeCollection tables = doc.getChildNodes(NodeType.TABLE, true);
//		for (Table table : (Iterable<Table>) tables) {
//			for (Row row : table.getRows()) {
//				row.getRowFormat().setHeight(10);
//				row.getRowFormat().setHeightRule(HeightRule.AUTO);
//			    for(Cell cell : row.getCells()) {
//			    	cell.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
//			    	cell.getCellFormat().setVerticalMerge(CellMerge.FIRST);
//			    }
//			}
//		}	
		
//		doc.getFirstSection().getBody().appendChild(new Paragraph(doc));
//		builder.moveToDocumentEnd();
		int index = 0;
		int sectionIndex = 0;
		for(Section section : doc.getSections()) {
			String sectionText = section.getText().trim();
			if(sectionText.contains("目录")) {
				builder.moveToSection(sectionIndex);
				break;
			}
			if(sectionText.contains("评估说明")) {
				index++;
				if(index != 1) {
					builder.moveToSection(sectionIndex);
					break;
				}
			}
			sectionIndex++;
		}
		//设置目录的格式         
		//“目录”两个字居中显示、黑体
		Paragraph p = builder.getCurrentParagraph();
		if(p == null) {
			p = builder.insertParagraph();
		}
		builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
//		builder.setBold(true);
		builder.getFont().setName("黑体");
		builder.getFont().setSize(16);
		builder.writeln("目    录");
		
		//清除所有样式设置
		if(type == 1) {
			builder.getParagraphFormat().clearFormatting();
			builder.getCurrentParagraph().getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
			builder.getFont().setName("黑体");
			builder.getFont().setSize(12);
			builder.writeln("第一册（声明、摘要、正文及附件）");
		}
		//插入目录，这是固定的
		builder.insertTableOfContents("\\o \"1-3\" \\h \\z \\u");
//		builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
//		builder.insertBreak(BreakType.PAGE_BREAK);
		doc.updateFields();
		
		doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_1).getFont().setSize(12);    //改变目录的字体大小
		doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_2).getFont().setSize(12);    //改变目录的字体大小
		doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getFont().setSize(12);    //改变目录的字体大小
		doc.getStyles().getByStyleIdentifier(StyleIdentifier.TOC_3).getParagraphFormat().setLineSpacing(18);//改变目录行距
        

		//清除所有样式设置
//		builder.getParagraphFormat().clearFormatting();
//		builder.getCurrentParagraph().getParagraphFormat().setFirstLineIndent(2);
//		//目录居左
//		builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
//		builder.getFont().setSize(12);
//		builder.getParagraphFormat().setLineSpacing(1.5);
//      doc.updatePageLayout();
        doc.save(filePath);

	}
	
	public static void testTable(String filePath) throws Exception {
		Document doc = new Document(filePath);
		DocumentBuilder builder = new DocumentBuilder(doc);
//		Table table = builder.startTable();
//		builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
//		builder.getFont().setSize(12);
//		builder.getFont().setName("Arial");
//		Cell cell = builder.insertCell();
//		builder.write("id");
//		builder.endRow()
//		builder.endTable();
//		doc.importNode(table, true);
		doc.save("C:\\Users\\Administrator\\Desktop\\t_12.doc");
	}
	
	public static void main(String[] args) {
		try {
			File file = new File("D:\\MyEclipseWorkspace\\word-server\\资产评估说明-收视_20200713143438.docx");
			InputStream is = new FileInputStream(file);
			XWPFDocument doc2 = new XWPFDocument(is);
			doc2.enforceUpdateFields();
//			int pages = doc2.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页数
//			int wordCount = doc2.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格bai的du总字符数 另外还有zhigetCharactersWithSpaces()方法获取带空格的总字数。
//			
//			System.out.println(pages);
//			System.out.println(wordCount);
//			doc2.getProperties().getExtendedProperties().getUnderlyingProperties().setPages(57);
//			System.out.println(doc2.getProperties().getExtendedProperties().getUnderlyingProperties().getPages());
			FileOutputStream fos = new FileOutputStream(file);
			doc2.write(fos);
			fos.flush();
			fos.close();
			doc2.close();
			
//			if (!getLicense()) { // 验证License 若不验证则会有水印产生
//				return;
//			}
//			doc2pdf("D:\\MyEclipseWorkspace\\word-server\\tt.doc", "D:\\MyEclipseWorkspace\\word-server\\资产评估说明-收视_20200708183428.pdf");
//			pdf2doc("D:\\MyEclipseWorkspace\\word-server\\资产评估说明-收视_20200708183428.pdf");
//			Document doc = new Document("D:\\MyEclipseWorkspace\\word-server\\aa1.docx");
//			doc.updatePageLayout();
//			doc.updateFields();
//			doc.save("D:\\MyEclipseWorkspace\\word-server\\aa11111.docx");
//			testTable("C:\\Users\\Administrator\\Desktop\\t_1.doc");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
